package org.itboys.mobile.service.mysql.web.product;


import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.service.lasted.SundayUploadService;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mobile.entity.mysql.product.SundayProductCategory;

import org.itboys.mongodb.service.BaseMySqlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_商品_类目_service_web
 * 当前为单规格。如果需要多规格，请自行扩展
 */

@Service
public class SundayProductCategoryService extends BaseMySqlService<SundayProductCategory> {
	@Autowired
	private SundayUploadService uploadService;
	@Autowired
	private ResourceHolder resourceHolder;


	/**
	 * 
	 * 获取商品类目的类目。树结构类型。
	 */
	public List<SundayProductCategory> getCategoryTreeJson(){
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("sort","sequence");
		param.put("order","asc");
		List<SundayProductCategory> all= super.select(param);
		List<SundayProductCategory> parents = new ArrayList<SundayProductCategory>();
		List<SundayProductCategory> children = new ArrayList<SundayProductCategory>();

		for(SundayProductCategory c:all){
			if(StringUtils.isNotEmpty(c.getImage())){
				c.setImage(resourceHolder.getStringValue("imgRoot")+c.getImage());
			}else{
				c.setImage(null);
			}

			if(c.getParentId().longValue()==0l){
				parents.add(c);
			}else{
				children.add(c);
			}
		}
		//组装TREE
		for(SundayProductCategory parent:parents){
			List<SundayProductCategory> child = new ArrayList<SundayProductCategory>();
			for(SundayProductCategory c:children){
				if(LongUtil.isNotZreo(c.getParentId())&&
						c.getParentId().longValue()==parent.getId().longValue()){
					child.add(c);
				}
			}
			parent.setChildren(child);
		}
		return parents;
	}

	/**
	 * 新增或修改分类
	 * @param category
	 * @param imageFile
	 * @throws Exception
	 */
	public void save(SundayProductCategory category,MultipartFile imageFile) throws Exception{
		Map<String, String> map = uploadService.uploadSingle(imageFile);
		if(StringUtils.isNotEmpty(map.get(uploadService.UPLOAD_HALF_PATH))){
			category.setImage(map.get(uploadService.UPLOAD_HALF_PATH));
		}
		if(LongUtil.isNotZreo(category.getId())){
			if(LongUtil.isNull(category.getParentId())){
				category.getParentId();
			}
			super.update(category);
		}else{
			super.insert(category);
		}
	}
	/**
	 * 删除商品类目
	 * @param categoryId
	 */
	public void deleteCategory(Long categoryId){
		super.delete(categoryId);
		logger.info("删除商品类目","id="+categoryId);
	}

}
